<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>Promise testDemo</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}

</style>
</head>
<body>
	<h1>aaaa</h1>
	<div id="box">
		<h2>第九章 闭包与作用域</h2>
		<button>收藏课程</button>
	</div>
</body>
<script src="index.js"></script>
<script type="text/javascript"> 

	function ajax(url) {
		return new Promise((resolve, reject) => {
			let xhr = new XMLHttpRequest();
			xhr.open("GET", url);

			// try{
			// 	xhr.send();
			// }catch(err) {
			// 	console.warn('xhr.send()', error, typeof error, error.constructor.name)
			// }
			xhr.send();

			xhr.onload = function() {
				console.log('3333 onload')
				
				if (this.status == 200) {
					try{
						resolve(JSON.parse(this.response));
					} catch(err) {
						reject(err);
					}
				} else {
					reject(this);
				}
			};

			xhr.onerror = function(evt) {
				console.log('onerror 4444')
				reject(new Error('onerror 错误'));
			}
		});
	}

	async function get(name) {

		try{
			let r = await ajax(`http://localhost/ajax4/ajax3.php?type=query&t=1&name=${name}`);
			console.log(r)
			console.log('如果await的promise失败了, 就会抛出异常, 需要通过 try...catch 捕获处理')
			return r
			
		}catch(err) {
			console.warn('await ajax', err, typeof err, err.constructor.name)
			throw err ;
		}
	}
	var name = "向军小哥";
	var url = `http://localhost/ajax3/ajax3.php?type=query&t=1&name=${name}`;

	if(0) {
		var p1 = ajax(url);
		p1.then(value => {}, reason => {
			console.warn(reason)
		})
	} else {
		get("向军小哥").catch(error => {
			console.log(error, typeof error, error.constructor.name)
		}).then(data => {
			console.log(data)
		});

	}
	
	

</script>
</html>